import { Component, OnInit, Output, Input, EventEmitter } from '@angular/core';
import { NzMessageService } from 'ng-zorro-antd';
import { _HttpClient } from '@delon/theme';
import { DatePipe } from '@angular/common';
import { Params, Router, ActivatedRoute } from '@angular/router';
import { environment } from '../../../../environments/environment';
import { forkJoin } from 'rxjs';

@Component({
    selector: 'app-operamodal',
    templateUrl: './operaModal.component.html',
    styleUrls: ['./safeHiddenDanger.component.less']
})
export class OperaModalComponent implements OnInit {
    @Input() operaWidth: any;
    @Input() apiUrl: any;
    @Input() operaType: any;
    @Input() responseData: any;
    @Input() popTitle: any;
    @Input() operaText: any;
    @Output() public closeModal = new EventEmitter();
    @Output() public reloadData = new EventEmitter();

    Visible = false;
    operaData: any = {};
    objData: any = {};
    delData: any = { 'count': 0, 'id': [] };
    tbbmNodes = [];
    zrbmNodes = [];
    phbmNodes = [];
    dbbmNodes = [];
    bmList = [];
    yhdjSelect = ["一般", "突出", "重大"];
    sfxhSelect = [
        { "value": "0", "label": "未销号" },
        { "value": "1", "label": "申请销号" },
        { "value": "2", "label": "销号驳回" },
        { "value": "3", "label": "已销号" }
    ];
    dyhkStatus = false;
    treeNodeStyle = { 'max-height': '300px', 'overflow-y': 'auto', 'overflow-x': 'hidden' };

    constructor(
        private msg: NzMessageService,
        private router: Router,
        private activatedRoute: ActivatedRoute,
        private datePipe: DatePipe,
        private http: _HttpClient
    ) { }

    ngOnInit() {
        if (!this.operaWidth) {
            this.operaWidth = '500';
        }
        switch (this.operaType) {
            case 'add':
                this.getApi('update', () => {
                    // 参数有ID表示从问题库转过来的
                    this.activatedRoute.queryParams.subscribe((params: Params) => {
                        if (params.id) {
                            this.dyhkStatus = true;
                            this.apiUrl = environment.project + '/safeProblem/toHideProblem';
                            this.operaData.sourceId = params.id;
                            this.operaData.submitOrgId = params.checkOrgId;
                            this.operaData.discoverDate = params.checkDate;
                            this.operaData.problemDesc = params.problemDesc
                            this.operaData.measure = params.handleRequire;
                            this.operaData.chargeOrgId = params.chargeOrgId;
                            this.operaData.deadline = params.deadline;
                            this.operaData.handleInfo = params.handleRequire;
                            delete this.operaData.id;
                        }
                    });
                });
                break;
            case 'edit':
                let editStatus = false;
                let editCount = 0;
                for (const item of this.responseData) {
                    if (item.checked) {
                        editCount += 1;
                        this.objData = item;
                        editStatus = true;
                    }
                }
                if (editStatus && editCount === 1) {
                    this.getApi('update', () => {
                        // 回填数据 
                        this.operaData.id = this.objData.id;
                        this.operaData.submitOrgId = this.objData.submitOrgId;
                        this.operaData.problemName = this.objData.problemName;
                        this.operaData.discoverDate = this.objData.discoverDate;
                        this.operaData.problemLevel = this.objData.problemLevel;
                        this.operaData.problemDesc = this.objData.problemDesc;
                        this.operaData.reason = this.objData.reason;
                        this.operaData.measure = this.objData.measure;
                        this.operaData.goal = this.objData.goal;
                        this.operaData.chargeOrgId = this.objData.chargeOrgId;
                        this.operaData.assistOrgId = this.objData.assistOrgId.split(',');
                        this.operaData.superviceOrgId = this.objData.superviceOrgId;
                        this.operaData.deadline = this.objData.deadline;
                        this.operaData.leader = this.objData.leader;
                        this.operaData.handleInfo = this.objData.handleInfo;
                    });
                } else {
                    this.Cancel();
                    this.msg.error('请选择一条数据进行操作');
                }
                break;
            case 'del':
            case 'sqxh':
            case 'pz':
            case 'bh':
            case 'sqrk':
            case 'pzrk':
            case 'bhrk':
            case 'zgwt':
                let delStatus = false;
                for (const item of this.responseData) {
                    if (item.checked) {
                        this.objData = item;
                        this.delData.count += 1;
                        this.delData.id.push(item.id)
                        delStatus = true;
                    }
                }
                if (delStatus) {
                    this.getApi('opera', () => {
                        // to do
                    });
                } else {
                    this.Cancel();
                    this.msg.error('请选择一条数据进行操作');
                }
                break;
        }
    }
    getApi(type, callback) {
        this.Visible = true;
        setTimeout(() => {
            switch (type) {
                case 'update':
                    const allApi = [
                        this.http.get(environment.apiBase + '/csmis/getKmnOrgTree.jwt?showAll=1&showSeg=1')
                    ];
                    forkJoin(allApi).subscribe((results: any) => {
                        this.childToList(this.bmList, results[0]);
                        Object.assign(this.tbbmNodes, results[0]);
                        Object.assign(this.zrbmNodes, results[0]);
                        Object.assign(this.phbmNodes, results[0]);
                        Object.assign(this.dbbmNodes, results[0]);
                        callback();
                    });
                    break;
                default:
                    callback();
                    break;
            }

        }, 200);
    }
    // children转list
    childToList(array, list) {
        list.forEach(item => {
            array.push(item);
            if (item.children && item.children.length > 0) {
                this.childToList(array, item.children);
            }
        })
    }
    Ok() {
        let param: any = {};
        switch (this.operaType) {
            case 'add':
            case 'edit':
                if (!this.operaData.submitOrgId || !this.operaData.problemName || !this.operaData.discoverDate ||
                    !this.operaData.problemLevel || !this.operaData.problemDesc || !this.operaData.reason ||
                    !this.operaData.measure || !this.operaData.goal || !this.operaData.chargeOrgId ||
                    !this.operaData.assistOrgId.length || !this.operaData.superviceOrgId ||
                    !this.operaData.deadline || !this.operaData.leader || !this.operaData.handleInfo
                ) {
                    this.msg.error('必填项不能为空', { nzDuration: 1000 });
                    return;
                }
                Object.assign(param, this.operaData);
                param.assistOrgName = [];
                for (const item of this.bmList) {
                    if (item.key === param.submitOrgId) {
                        param.submitOrgName = item.title;
                    }
                    if (item.key === param.chargeOrgId) {
                        param.chargeOrgName = item.title;
                    }
                    for (const list of param.assistOrgId) {
                        if (item.key === list) {
                            param.assistOrgName.push(item.title);
                        }
                    }
                    if (item.key === param.superviceOrgId) {
                        param.superviceOrgName = item.title;
                    }
                }
                param.assistOrgId = param.assistOrgId.join();
                param.assistOrgName = param.assistOrgName.join();
                param.discoverDate = this.datePipe.transform(param.discoverDate, 'yyyy-MM-dd');
                param.deadline = this.datePipe.transform(param.deadline, 'yyyy-MM-dd');
                if (this.operaType === 'edit') {
                    param.id = this.operaData.id;
                }
                break;
            case 'del':
                param = this.delData.id;
                break;
            case 'sqxh':
            case 'sqrk':
                param = new FormData();
                param.append('id', this.delData.id);
                break;
            case 'pz':
            case 'bh':
            case 'pzrk':
            case 'bhrk':
            case 'zgwt':
                if (!this.operaData.advice) {
                    this.msg.error('审批意见不能为空', { nzDuration: 1000 });
                    return;
                }
                param = new FormData();
                param.append('id', this.delData.id);
                if (this.operaType === 'zgwt') {
                    param.append('info', this.operaData.advice);
                } else {
                    param.append('advice', this.operaData.advice);
                }
                break;
        }
        this.http.post(this.apiUrl, param).subscribe((res: any) => {
            if (!res.code) {
                this.Visible = false;
                setTimeout(() => {
                    this.closeModal.emit();
                    this.reloadData.emit();
                    if (this.dyhkStatus) {
                        this.router.navigate(['securityProblem/edit']);
                    }
                }, 200);
            } else {
                this.msg.error(res.msg);
            }
        });
    }

    Cancel() {
        this.Visible = false;
        setTimeout(() => {
            this.closeModal.emit();
            if (this.dyhkStatus) {
                this.router.navigate(['securityProblem']);
            }
        }, 200);
    }
}